<!-- 活动管理 -->
<template>
  <a-card :bordered="false" class="br-10">
    <div class="table-page-search">
      <a-form>
        <a-form-item label="活动名称:">
          <a-input v-model="queryParam.title" placeholder="请输入活动名称" allowClear />
        </a-form-item>
        <a-form-item label="展示状态:">
          <a-select v-model="queryParam.display" placeholder="请选择展示状态" allowClear style="width: 150px">
            <a-select-option v-for="(item, i) in displayDict" :key="i" :value="item.dictValue">{{
              item.dictLabel
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="发布状态:">
          <a-select v-model="queryParam.publishStatus" placeholder="请选择状态" allowClear>
            <a-select-option v-for="(item, i) in publishStatusDict" :key="i" :value="item.dictValue">{{
              item.dictLabel
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="活动状态:">
          <a-select v-model="queryParam.activityStatus" placeholder="请选择状态" allowClear>
            <template v-for="(item, i) in activityStateDict">
              <a-select-option v-if="item.dictValue <= 6" :key="i" :value="item.dictValue">{{
                item.dictLabel
              }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="活动创建人:">
          <a-input v-model="queryParam.createByName" placeholder="请输入活动创建人" allowClear />
        </a-form-item>

        <span class="search-submitButtons">
          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </span>
      </a-form>
    </div>
    <div class="table-operator disFlxJS">
      <div>
        <a-button v-has="'activity:activityList:add'" type="primary" @click="handleAdd">新建活动</a-button>
      </div>
      <div></div>
    </div>
    <s-table
      size="default"
      ref="table"
      rowKey="userId, title"
      :rowSelection="null"
      :columns="newColumns"
      :data="loadData"
      :rangPicker="range"
    >
      <!-- 序号 -->
      <span slot="serial" slot-scope="text, record, index">
        {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
      </span>

      <!-- 序号 -->
      <div slot="minPrice" slot-scope="text, record">
        <template v-if="record.minPrice == record.maxPrice || !record.maxPrice">{{ record.minPrice }}</template>
        <template v-else>{{ record.minPrice }}~{{ record.maxPrice }}</template>
      </div>

      <!--  身份 -->
      <div slot="identity" slot-scope="text">
        <DictTag :options="Dict.getLocal('activityTypeDict')" :value="text" />
      </div>

      <!--  是否对外展示 -->
      <span slot="display" slot-scope="text, record">
        <a-switch
          :key="record.id"
          :defaultChecked="record.display == displayEnum.SHOW"
          @change="val => onChangeDisplay(record.id, val)"
        />
      </span>

      <!--  待审核 -->
      <span slot="waitingReviewNum" slot-scope="text">
        <span style="color: #faad14">{{ text || 0 }}</span>
      </span>

      <!-- 发布状态 -->
      <span slot="publishStatus" slot-scope="text">
        <DictTag :options="Dict.getLocal('publishStatusDict')" :value="text" isText />
      </span>
      <!-- 活动状态 -->
      <span slot="activityStatus" slot-scope="text">
        <DictTag :options="Dict.getLocal('activityStateDict')" :value="String(text)" isBadge />
      </span>

      <!-- 活动时间 -->
      <span slot="time" slot-scope="text, record">
        <div>{{ record.startTime | filterTime }} ~</div>
        <div>{{ record.endTime | filterTime }}</div>
      </span>

      <!-- 报名成功人数 -->
      <span slot="passedNum" slot-scope="text">
        <span style="color: #52c41a">{{ text }}</span>
      </span>

      <!-- 操作 -->
      <div slot="actionFilterIcon" class="disFlxAC min-width-12">
        <CustomTable :name="$route.name" :columns="columns" :newColumns="newColumns" />
      </div>
      <template slot="actionFilter">
        <div></div>
      </template>
      <div slot="action" slot-scope="text, record" class="disFlxAC flexWrap">
        <ButtonGroup :max-length="2" :key="`${record.id}-${record.publishStatus}-${record.sort}`">
          <a-button
            v-for="item in _btnList(record)"
            :key="item.text"
            :type="item.type"
            :ghost="item.ghost"
            size="small"
            class="width-8"
            @click="item.fn"
          >
            {{ item.text }}
          </a-button>
        </ButtonGroup>
      </div>
    </s-table>
    <!-- 分享活动 -->
    <ShareModal ref="ShareModal" />
    <DashboardGuide />
  </a-card>
</template>

<script>
import { STable } from '@/components'
import {
  getUnionActivityList,
  editSection,
  activityDisplay,
  ActivityTop,
  ActivityRemoveTop,
  generateUrlLink
} from '@/api/activity/activity'
import { memberLevelGetDownList } from '@/api/system/system'
import CustomTable from '@/components/Cuscolumn'
import DictTag from '@/components/DictTag'
import ButtonGroup from '@/components/Table/buttonGroup'
import { checkPermission } from '@/utils/authority'
import { activityTypeEnum, publishStatusEnum, displayEnum } from '@/enums/activity'
import ShareModal from '@/components/ShareModal/index.vue'
import DashboardGuide from './components/DashboardGuide/index.vue'
export default {
  components: {
    STable,
    CustomTable,
    DictTag,
    ButtonGroup,
    ShareModal,
    DashboardGuide
  },
  data() {
    return {
      displayEnum,
      pagination: {
        current: 1,
        pageSize: 10
      },
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 查询参数
      queryParam: {
        title: undefined,
        reviewerName: undefined,
        createByName: undefined,
        publishStatus: undefined,
        activityStatus: undefined,
        beginDate: undefined,
        endDate: undefined,
        startTime: undefined,
        endTime: undefined
      },
      // 活动表单
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          width: 100
        },
        {
          title: '活动名称',
          dataIndex: 'title',
          width: 200
        },
        {
          title: '活动时间',
          width: 200,
          scopedSlots: { customRender: 'time' }
        },
        {
          title: '报名费用',
          width: 200,
          scopedSlots: { customRender: 'minPrice' }
        },
        {
          title: '是否对外展示',
          dataIndex: 'display',
          width: 120,
          ellipsis: true,
          scopedSlots: { customRender: 'display' }
        },
        {
          title: '身份',
          dataIndex: 'activityType',
          width: 200,
          scopedSlots: { customRender: 'identity' }
        },
        {
          title: '发起单位',
          dataIndex: 'orgName',
          width: 200
        },
        {
          title: '发布状态',
          dataIndex: 'publishStatus',
          width: 120,
          ellipsis: true,
          scopedSlots: { customRender: 'publishStatus' }
        },
        {
          title: '活动状态',
          dataIndex: 'activityStatus',
          width: 120,
          scopedSlots: { customRender: 'activityStatus' }
        },
        {
          title: '待审核',
          dataIndex: 'waitingReviewNum',
          width: 100,
          scopedSlots: { customRender: 'waitingReviewNum' }
        },

        {
          title: '浏览次数',
          dataIndex: 'browseNum',
          width: 100
        },
        {
          title: '报名人数',
          dataIndex: 'registerNum',
          width: 100
        },
        {
          title: '报名成功',
          dataIndex: 'passedNum',
          width: 100,
          scopedSlots: { customRender: 'passedNum' }
        },
        {
          title: '创建人',
          dataIndex: 'createByName',
          width: 100
        },

        {
          title: '操作',
          width: '245px',
          fixed: 'right',
          scopedSlots: {
            customRender: 'action',
            filterDropdown: 'actionFilter',
            filterIcon: 'actionFilterIcon'
          }
        }
      ],
      range: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getUnionActivityList(Object.assign(parameter, this.queryParam))
      },
      drd: {
        member_level_list: []
      }
    }
  },
  computed: {
    displayDict() {
      return this.Dict.getLocal('displayDict')
    },
    publishStatusDict() {
      return this.Dict.getLocal('publishStatusDict')
    },
    activityStateDict() {
      return this.Dict.getLocal('activityStateDict')
    },
    createTime: {
      get() {
        return [this.queryParam.beginDate, this.queryParam.endDate]
      },
      set(val) {
        this.queryParam.beginDate = val[0]
        this.queryParam.endDate = val[1]
      }
    },
    startTime: {
      get() {
        return [this.queryParam.startTime, this.queryParam.endTime]
      },
      set(val) {
        ;(this.queryParam.startTime = val[0]), (this.queryParam.endTime = val[1])
      }
    },
    newColumns() {
      const currentColumns = this.$store.state.user.customTable
      if (currentColumns && currentColumns[this.$route.name]) {
        return this.$options
          .data()
          .columns.filter(v => {
            const _items = currentColumns[this.$route.name].find(item => item === v.title || item.title === v.title)
            if (_items) return Object.assign(v, _items)
          })
          .sort((a, b) => {
            return a.tableSort - b.tableSort
          })
      } else {
        return this.columns
      }
    }
  },

  created() {
    this.getMemberLevelGetDownList()
  },
  mounted() {},
  methods: {
    _btnList(record) {
      let oldList = [
        {
          show: checkPermission('activity:activityDetail'),
          text: '管理',
          fn: () => this.handleDetail(record)
        },
        {
          show: true,
          text: '分享推广',
          fn: async () => {
            this.$refs.ShareModal.openModel(record.id, '分享推广')
          }
        },
        {
          show: record.activityType !== activityTypeEnum.other_join, // 协办方不能操作发布状态
          text:
            record.publishStatus === publishStatusEnum.UNISSUE
              ? '发布活动'
              : record.publishStatus === publishStatusEnum.ISSUE
              ? '下架活动'
              : '上架活动',
          type: record.publishStatus === publishStatusEnum.ISSUE ? 'danger' : 'primary',
          ghost: true,
          fn: () => this.updatePublishStatus(record)
        },
        {
          show: true,
          text: record.sort ? '取消置顶' : '置顶活动',
          type: 'primary',
          ghost: true,
          fn: () => (record.sort ? this.handleRemoveTop(record.id) : this.handleTop(record.id))
        },
        {
          show: record.activityType !== activityTypeEnum.other_join && record.publishStatus === publishStatusEnum.ISSUE,
          text: '邀请合作',
          type: 'primary',
          ghost: true,
          fn: () => this.$router.push({ path: '/activity/coOrganizer', query: { activityId: record.id } })
        }
      ]
      return oldList.filter(v => v.show)
    },
    handleReload() {
      this.$refs.table.refresh()
    },
    handleReset() {
      Object.keys(this.queryParam).forEach(k => {
        this.queryParam[k] = undefined
      })
      this.$refs.table.refresh(true)
    },
    // 活动列表新增
    handleAdd() {
      this.$router.push({
        path: '/activity/activityUpdate',
        query: { timestamp: Date.now() }
      })
    },
    //活动切换是否对外展示
    async onChangeDisplay(id, display) {
      let { code, msg } = await activityDisplay({
        id,
        display: display ? displayEnum.SHOW : displayEnum.HIDE
      })
      this.$message[code === 0 ? 'success' : 'error'](msg)
      if (code === 0) {
        this.handleReload()
      }
    },
    handleDetail(record) {
      this.$router.push({
        path: '/activity/activityDetail',
        query: {
          activityId: record.id
        }
      })
    },
    async getMemberLevelGetDownList() {
      let res = await memberLevelGetDownList()
      this.drd.member_level_list = res.data || []
    },
    //置顶
    async handleTop(id) {
      await ActivityTop(id)
      this.$message.success('置顶成功')
      this.handleReload()
    },
    async handleRemoveTop(id) {
      await ActivityRemoveTop(id)
      this.$message.success('取消置顶成功')
      this.handleReload()
    },
    async updatePublishStatus(row) {
      const that = this
      // 已发布操作下架,其它状态都只能更改为已发布
      const updateStatus =
        row.publishStatus === publishStatusEnum.ISSUE ? publishStatusEnum.SOLDOUT : publishStatusEnum.ISSUE
      const updateText =
        row.publishStatus === publishStatusEnum.UNISSUE
          ? '发布'
          : row.publishStatus === publishStatusEnum.ISSUE
          ? '下架'
          : '上架'
      that.$confirm({
        title: `${updateText}活动`,
        content: `确定要${updateText}活动吗？${
          updateStatus === 2 ? '活动下架后将无法再报名，同时将在本组织、协办组织的活动列表全部下架不显示。' : ''
        }`,
        okText: `确定${updateText}`,
        cancelText: '取消',
        onOk() {
          return new Promise((resolve, reject) => {
            editSection({ id: row.id, publishStatus: updateStatus })
              .then(() => {
                that.$message.success(`${updateText}成功`)
                that.handleReload()
                resolve()
              })
              .catch(err => {
                reject(err)
              })
          })
        }
      })
    }
  },
  provide() {
    return {
      drd: () => this.drd
    }
  },
  // 表格状态 引入activityState使用
  filters: {
    filterTime(val) {
      if (!val) return
      return val.substring(0, val.length - 3)
    }
  }
}
</script>
<style scoped lang="less"></style>
